package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.SsSession;
import cn.com.hhrcw.mapstruct.SsSessionAdminConvert;
import cn.com.hhrcw.params.SsSessionAdminParams;
import cn.com.hhrcw.params.SsSessionParams;
import cn.com.hhrcw.service.IOpJobService;
import cn.com.hhrcw.service.ISsSessionService;
import cn.com.hhrcw.vo.SsSessionAdminVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

/**
 * 专场-专场本场
 *
 * @author gaoruiyi
 * @since 2020-11-02
 */
@Slf4j
@Api(tags = "专场-专场本场")
@Validated
public class SsSessionAdminController extends JeecgController<SsSession, ISsSessionService> {

    @Autowired
    private ISsSessionService ssSessionService;

    @Autowired
    private SsSessionAdminConvert ssSessionAdminConvert;

    @Autowired
    private IOpJobService jobService;

    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(value = "专场列表",logType = 2,ty = "visit")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<SsSessionAdminVO>> list(SsSessionAdminParams params, HttpServletRequest request) {
        QueryWrapper<SsSession> queryWrapper = QueryGenerator.initQueryWrapper(ssSessionAdminConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<SsSession> page = ssSessionService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<SsSession, SsSessionAdminVO> fun = ssSession -> ssSessionAdminConvert.toVO(ssSession);

        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @AutoLog(value = "专场信息查询",logType = 2,ty = "visit")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<SsSessionAdminVO> queryById(String id) {
        SsSession ssSession = ssSessionService.lambdaQuery().eq(SsSession::getId, id).eq(SsSession::getDelFlag, false).one();
        if (ssSession == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(ssSessionAdminConvert.toVO(ssSession));
    }

    /**
     * 添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog(value = "专场添加",logType = 2,ty = "insert")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("session:add")
    public Result<?> add(@RequestBody @Valid SsSessionAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession ssSession = ssSessionAdminConvert.toEntity(params);
        ssSession.setCreateBy(sysUser.getId());
        ssSession.setCreateTime(DateUtil.date());
        ssSession.setDelFlag(false);
        ssSession.setRecommendFlag(0);
        ssSession.setPubFlag(false);

        //ssSession.setNo(super.sort("ss_session", Constant.NO_SEED));//FIXME: 编号,可根据情况隐藏
        boolean saved = ssSessionService.save(ssSession);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(value = "专场编辑",logType = 2,ty = "update")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("session:edit")
    public Result<?> edit(@RequestBody @Valid SsSessionAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        SsSession ssSession = ssSessionAdminConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());

        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 取消发布专场
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/unPublish")
    @AutoLog(logType = 2, ty = "update", value = "取消发布专场")
    @ApiOperation(value = "取消发布专场", notes = "取消发布专场")
    @RequiresPermissions("session:publish")
    public Result<?> unPublish(@RequestBody @Valid SsSessionAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession ssSession = ssSessionAdminConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());
        ssSession.setPubFlag(false);
        ssSession.setUpdateTime(new Date());
        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 发布此专场
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/publish")
    @AutoLog(value = "发布专场",logType = 2,ty = "update")
    @ApiOperation(value = "发布此专场", notes = "发布此专场")
    @RequiresPermissions("session:edit")
    public Result<?> publish(@RequestBody @Valid SsSessionAdminParams params) {
        int jobCount = jobService.lambdaQuery().eq(OpJob::getBsType, 1).eq(OpJob::getBsId, params.getId()).count();
        if (jobCount == 0) {
            return Result.error("该专场未完善职位。");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        SsSession ssSession = ssSessionAdminConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());
        ssSession.setPubFlag(true);
        ssSession.setPubTime(new Date());
        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 专场推荐
     *
     * @param params
     * @return
     */
    @PostMapping("/recommended")
    @AutoLog(value = "专场推荐",logType = 2,ty = "update")
    @RequiresPermissions("session:recommended")
    public Result recommended(@RequestBody SsSessionAdminParams params) {
        SsSession session = this.ssSessionService.getById(params.getId());
        int flag = session.getRecommendFlag() == 0 ? 1 : 0;
        session.setRecommendFlag(flag);
        if(flag == 1) {
            session.setRecommendSort(params.getRecommendSort());
        }
        boolean updated = this.ssSessionService.updateById(session);
        return updated ? Result.ok() : Result.error("推荐失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(value = "专场删除",logType = 2,ty = "delete")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("session:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<SsSession> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(SsSession::getId, id).set(SsSession::getDelFlag, true).set(SsSession::getUpdateBy, sysUser.getUsername()).set(SsSession::getUpdateTime, DateUtil.date());

        boolean deleted = ssSessionService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, SsSessionAdminParams params) {
        SsSession ssSession = ssSessionAdminConvert.toEntity(params);
        ssSession.setDelFlag(false);
        QueryWrapper<SsSession> queryWrapper = QueryGenerator.initQueryWrapper(ssSession, request.getParameterMap());
        List<SsSession> data = ssSessionService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("专场-专场本场", "专场-专场本场");
        String url = super.exportXls(exportParams, SsSessionAdminVO.class, ssSessionAdminConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SsSession.class);
    }

}
